package com.zzty.zzlp.controller;

import com.zzty.zzlp.commom.ChatFileUpLoad;
import com.zzty.zzlp.entity.Chat;
import com.zzty.zzlp.entity.ChatBuffer;
import com.zzty.zzlp.entity.ChatUser;
import com.zzty.zzlp.entity.User;
import com.zzty.zzlp.service.ChatService;
import com.zzty.zzlp.socket.SessionUtils;
import com.zzty.zzlp.socket.SocketHandler;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.socket.TextMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.io.File;


@RestController
public class ChatController {
    private static final Logger logger;


    static {

        logger = LoggerFactory.getLogger(SocketHandler.class);
    }

    @Autowired
    ChatService chatService;

    @Autowired
    private SocketHandler socketHandler;


    @RequestMapping(path = "/searchUsers", method = RequestMethod.GET)
    public String searchUsers(HttpServletRequest request) {
        //List<User> userList = chatService.searchUsers();
        User user = (User) request.getSession().getAttribute("User");
        List<ChatUser> chatUserList = chatService.searchUsersAndLastMessage(user.getId());
//        System.out.println(userList.size());


        JSONArray array = JSONArray.fromObject(chatUserList);
        return array.toString();
    }


    @RequestMapping(value = "/sendToUser", method = RequestMethod.POST)
    public String sendMessage(@RequestBody Chat chat, HttpServletRequest request) {


        User user = (User) request.getSession().getAttribute("User");
        chat.setFromId(user.getId());
        logger.info(chat.toString());
        if (SessionUtils.hasConnection(chat.getToId() + "")) {
            chat.setState(0);
            chatService.createChat(chat);
            if ("text".equals(chat.getType())) {
                JSONObject object = JSONObject.fromObject(chat);
                object.put("avatar",chatService.searchAvatar(user.getId()));
                socketHandler.sendMessageToUser(chat.getToId() + "", new TextMessage(object.toString()));
            } else if ("img".equals(chat.getType())) {
                JSONObject object = JSONObject.fromObject(chat);
                object.put("avatar",chatService.searchAvatar(user.getId()));
                socketHandler.sendMessageToUser(chat.getToId() + "", new TextMessage(object.toString()));
            } else if ("file".equals(chat.getType())) {
                JSONObject object = JSONObject.fromObject(chat);
                if ((chat.getMsg().endsWith(".doc")) || (chat.getMsg().endsWith(".docx"))) {
                    object.put("fileType", "word");
                    object.put("icon", "/zzlp/img/word.jpg");
                } else if (chat.getMsg().endsWith(".xls")) {
                    object.put("fileType", "excel");
                    object.put("icon", "/zzlp/img/excel.jpg");
                } else if (chat.getMsg().endsWith(".txt")) {
                    object.put("fileType", "txt");
                    object.put("icon", "/zzlp/img/txt.jpg");
                } else if ((chat.getMsg().endsWith(".zip")) || (chat.getMsg().endsWith(".rar"))) {
                    object.put("fileType", "zip");
                    object.put("icon", "/zzlp/img/zip.jpg");
                }else{
                    object.put("fileType", "file");
                    object.put("icon", "/zzlp/img/file1.jpg");
                }

                object.put("avatar",chatService.searchAvatar(user.getId()));
                socketHandler.sendMessageToUser(chat.getToId() + "", new TextMessage(object.toString()));

            }

        } else {
            chat.setState(0);
            chatService.createChat(chat);


        }

        return "message";
    }

    @RequestMapping(value = "/sendImgToUser", method = RequestMethod.POST)
    public String sendImgToUser(@RequestParam(value = "time") String time, @RequestParam(value = "toId") Integer toId, @RequestParam(value = "files") MultipartFile files, HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("User");
        Chat chat = new Chat();
        chat.setToId(toId);
        chat.setTime(time);
        chat.setType("img");
        chat.setFromId(user.getId());
        chat.setGroupId(0);
        chat.setIsGroup(0);
        Map<String, String> fileInfo = ChatFileUpLoad.uploadFile(files);
        String filePath = fileInfo.get("filename");
        chat.setMsg(filePath);
        System.out.println(chat.toString());
        if (SessionUtils.hasConnection(chat.getToId() + "")) {
            chat.setState(0);
            chatService.createChat(chat);
            JSONObject object = JSONObject.fromObject(chat);

            object.put("avatar",chatService.searchAvatar(user.getId()));
            socketHandler.sendMessageToUser(chat.getToId() + "", new TextMessage(object.toString()));
        } else {
            chat.setState(0);
            chatService.createChat(chat);


        }
        JSONObject object1 = JSONObject.fromObject(chat);
        System.out.println("----" + object1.toString());
        System.out.println("C:/temp/"+filePath);
        isExist("C:/temp/"+filePath);

        return object1.toString();
    }

    @RequestMapping(value = "/sendFileToUser", method = RequestMethod.POST)
    public String sendFileToUser(@RequestParam(value = "time") String time, @RequestParam(value = "toId") Integer toId, @RequestParam(value = "files") MultipartFile files, HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("User");
        Chat chat = new Chat();
        chat.setToId(toId);
        chat.setTime(time);
        chat.setType("file");
        chat.setFromId(user.getId());
        chat.setGroupId(0);
        chat.setIsGroup(0);
        Map<String, String> fileInfo = ChatFileUpLoad.uploadFile(files);
        String filePath = fileInfo.get("filename");
        chat.setMsg(filePath);
        System.out.println(chat.toString());
        if (SessionUtils.hasConnection(chat.getToId() + "")) {
            chat.setState(0);
            chatService.createChat(chat);

            JSONObject object = JSONObject.fromObject(chat);
            if ((chat.getMsg().endsWith(".doc")) || (chat.getMsg().endsWith(".docx"))) {
                object.put("fileType", "word");
                object.put("icon", "/zzlp/img/word.jpg");
            } else if (chat.getMsg().endsWith(".xls")) {
                object.put("fileType", "excel");
                object.put("icon", "/zzlp/img/excel.jpg");
            } else if (chat.getMsg().endsWith(".txt")) {
                object.put("fileType", "txt");
                object.put("icon", "/zzlp/img/txt.jpg");
            } else if ((chat.getMsg().endsWith(".zip")) || (chat.getMsg().endsWith(".rar"))) {
                object.put("fileType", "zip");
                object.put("icon", "/zzlp/img/zip.jpg");
            }else {
                object.put("fileType", "file");
                object.put("icon", "/zzlp/img/file1.jpg");

            }


            object.put("fileOldName",filePath.substring(filePath.indexOf("_")+1,filePath.length()));
            object.put("avatar",chatService.searchAvatar(user.getId()));
            socketHandler.sendMessageToUser(chat.getToId() + "", new TextMessage(object.toString()));
        } else {
            chat.setState(0);
            chatService.createChat(chat);


        }
        JSONObject object1 = JSONObject.fromObject(chat);
        if ((chat.getMsg().endsWith(".doc")) || (chat.getMsg().endsWith(".docx"))) {
            object1.put("fileType", "word");
            object1.put("icon", "/zzlp/img/word.jpg");
        } else if (chat.getMsg().endsWith(".xls")) {
            object1.put("fileType", "excel");
            object1.put("icon", "/zzlp/img/excel.jpg");
        } else if (chat.getMsg().endsWith(".txt")) {
            object1.put("fileType", "txt");
            object1.put("icon", "/zzlp/img/txt.jpg");
        } else if ((chat.getMsg().endsWith(".zip")) || (chat.getMsg().endsWith(".rar"))) {
            object1.put("fileType", "zip");
            object1.put("icon", "/zzlp/img/zip.jpg");
        }else{
            object1.put("fileType", "file");
            object1.put("icon", "/zzlp/img/file1.jpg");
        }
        System.out.println("----" + object1.toString());
        return object1.toString();
    }


    /* public static void main(String[] args) {
         ChatServiceImpl c=new ChatServiceImpl();
         System.out.println(c.searchUsers().toString());
     }*/
    @RequestMapping(value = "/searchAllMessage", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject searchAllMessage(@RequestBody Chat chat, HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute("User");

        String txtPath=chatService.creatAllMessageTXT(user.getId(), chat.getToId());
        System.out.println("txtPath:"+txtPath);
        JSONObject object = new JSONObject();
        object.put("path",txtPath);
        return object;
    }

    @RequestMapping(value = "/readMessageEnd", method = RequestMethod.POST)
    public void readMessageEnd(@RequestBody Chat chat, HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute("User");
        chatService.readMessageEnd(chat.getFromId(), user.getId());

    }
    @RequestMapping(value = "/searchUserId", method = RequestMethod.GET)
    public String searchUserId(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute("User");

        System.out.println("-------------------"+String.valueOf(user.getId()));
        return String.valueOf(user.getId());

    }


    @RequestMapping(value = "/readMessage", method = RequestMethod.POST)
    public String readMessage(@RequestBody Chat chat, HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute("User");
        List<ChatBuffer> chatList = chatService.readMessage(chat.getFromId(), user.getId());
        List<ChatBuffer> chatBufferList = new ArrayList<ChatBuffer>();
        for (int i = 0; i < chatList.size(); i++) {
            ChatBuffer chatBuffer = new ChatBuffer();
            chatBuffer.setId(chatList.get(i).getId());
            chatBuffer.setFromId(chatList.get(i).getFromId());
            chatBuffer.setGroupId(chatList.get(i).getGroupId());
            chatBuffer.setIsGroup(chatList.get(i).getIsGroup());
            chatBuffer.setState(chatList.get(i).getState());
            chatBuffer.setTime(chatList.get(i).getTime());
            chatBuffer.setToId(chatList.get(i).getToId());
            chatBuffer.setType(chatList.get(i).getType());
            chatBuffer.setMsg(chatList.get(i).getMsg());
            if ("file".equals(chatBuffer.getType())) {
                System.out.println("file");
                if ((chatBuffer.getMsg().endsWith(".doc")) || (chatBuffer.getMsg().endsWith(".docx"))) {
                    chatBuffer.setFileType("word");
                    chatBuffer.setIcon("/zzlp/img/word.jpg");
                } else if (chatBuffer.getMsg().endsWith(".xls")) {
                    chatBuffer.setFileType("excel");
                    chatBuffer.setIcon("/zzlp/img/excel.jpg");
                } else if (chatBuffer.getMsg().endsWith(".txt")) {
                    chatBuffer.setFileType("txt");
                    chatBuffer.setIcon("/zzlp/img/txt.jpg");
                } else if ((chatBuffer.getMsg().endsWith(".zip")) || (chatBuffer.getMsg().endsWith(".rar"))) {
                    chatBuffer.setFileType("zip");
                    chatBuffer.setIcon("/zzlp/img/zip.jpg");

                }else {
                    chatBuffer.setFileType("file");
                    chatBuffer.setIcon("/zzlp/img/file1.jpg");
                }


            } else if ("img".equals(chatBuffer.getType())) {
                System.out.println("img");

            } else if ("text".equals(chatBuffer.getType())) {
                System.out.println("text");

            }
            System.out.println(chatBuffer.toString());
            chatBufferList.add(chatBuffer);

        }


        JSONArray jsonArray = JSONArray.fromObject(chatBufferList);
        System.out.println("jsonArray:" + jsonArray.toString());
        return jsonArray.toString();
    }
    public static void isExist(String path) {
        File file = new File(path);
        //判断文件夹是否存在,如果不存在则创建文件夹
        if (!file.exists()) {
            System.out.println("不存在");
//            file.mkdir();
        }else{

            System.out.println("存在");
        }
    }

    @RequestMapping("getImgByFileName")
    public void getImgByFileName(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String name = request.getParameter("name").toString();
//        String imagePath = "/zzlp/resources/upload/chatFile/"+name;
//        FileInputStream fis = new FileInputStream(imagePath);
//        int size =fis.available(); //得到文件大小
//        byte data[]=new byte[size];
//        fis.read(data);  //读数据
//        fis.close();
//        response.setContentType("image/gif"); //设置返回的文件类型
//        OutputStream os = response.getOutputStream();
//        os.write(data);
//        os.flush();
//        os.close();
        System.out.println("img controller====");
    }
}
